package com.niiwoo.civet.user.service.duboo.dataflow;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.niiwoo.civet.user.dao.entity.MobileChangeRecord;
import com.niiwoo.civet.user.dao.entity.UcAccount;
import com.niiwoo.civet.user.dao.mapper.MobileChangeRecordMapperExt;
import com.niiwoo.civet.user.dao.mapper.UserAccountMapperExt;
import com.niiwoo.civet.user.dto.LinkManDubboInfoDTO;
import com.niiwoo.civet.user.dto.UserPersonalDubboInfoDTO;
import com.niiwoo.civet.user.dto.UserProfessionDubboInfoDTO;
import com.niiwoo.civet.user.dto.request.DataBackFlowRetryTaskRequestDTO;
import com.niiwoo.civet.user.dto.response.UserBasicInfoResponseDTO;
import com.niiwoo.civet.user.enums.*;
import com.niiwoo.civet.user.service.dataflow.DataBackFlowRetryDubboService;
import com.niiwoo.civet.user.service.dataflow.UserProfessionInfoBackFlowDubboService;
import com.niiwoo.civet.user.service.local.UserBasicInfoService;
import com.niiwoo.civet.user.service.local.UserDataService;
import com.niiwoo.tripod.base.component.PrivacyMasks;
import com.niiwoo.tripod.tiancheng.component.TianchengDataFlowService;
import com.niiwoo.tripod.tiancheng.enums.FunctionCodeEnum;
import com.niiwoo.tripod.tiancheng.request.common.TianchengUapRequest;
import com.niiwoo.tripod.tiancheng.request.df.ChangeMobileNoRequest;
import com.niiwoo.tripod.tiancheng.request.df.PersonalInfoRequest;
import com.niiwoo.tripod.tiancheng.request.df.ProfessionInfoRequest;
import com.niiwoo.tripod.tiancheng.response.common.TianchengUapResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;

/**
 * 天称数据回流服务
 * Created by HuangMin on 2018/04/19.
 */
@Slf4j
@Service(version = "1.0.0")
public class UserProfessionInfoBackFlowDubboServiceImpl implements UserProfessionInfoBackFlowDubboService {

    @Autowired
    PrivacyMasks privacyMasks;
    @Autowired
    TianchengDataFlowService tianchengDataFlowService;
    @Autowired
    UserAccountMapperExt userAccountMapperExt;
    @Autowired
    MobileChangeRecordMapperExt mobileChangeRecordMapper;
    @Autowired
    UserDataService userDataService;
    @Autowired
    UserBasicInfoService userBasicInfoService;

    @Reference(version = "1.0.0")
    private DataBackFlowRetryDubboService dataBackFlowRetryDubboService;


    @Override
    public void personalInfo(String userId) {
        log.info("UserProfessionInfoBackFlowDubboServiceImpl.personalInfo userId={} start", userId);

        UserPersonalDubboInfoDTO personalInfo = userDataService.userPersonalInfo(userId);
        UserBasicInfoResponseDTO userBasicInfo = userBasicInfoService.getUserBaseInfo(userId);

        PersonalInfoRequest infoRequest = new PersonalInfoRequest();
        infoRequest.setUserId(userId); //用户id
        infoRequest.setMobilePhone(userBasicInfo.getMobileNo()); //手机号

        Integer eduLevel = UserPersonalEnum.UserEduLevelEnum.getByLevel(personalInfo.getEducationLevel()).getTianChengUserEduLevelEnum().getType();
        infoRequest.setDegreeType(eduLevel); //学历--学历类型(1大专以下,2大专,3本科,4硕士,5博士及以上)

        Integer maritalStatus = UserPersonalEnum.UserMaritalStatusEnum.getByLevel(personalInfo.getMaritalStatus()).getTianChengUserMaritalStatusEnum().getStatus();
        infoRequest.setMaritalStatus(maritalStatus);//婚姻状况--(0未婚,1已婚,2离异,3丧偶)

        UserEnum.RegisterChannel registerChannel = UserEnum.RegisterChannel.enumOf(userBasicInfo.getRegisterChannel().byteValue());
        infoRequest.setFromType(TCFromTypeEnum.getTCFromTypeFromRegisterChannel(registerChannel)); ////用户来源(0-未知 1团贷网，2好帮贷，3你我金融，4房宝宝，5现金动车，6量化派 7 借钱快 8 融360 9卡牛)

        infoRequest.setLivingProvince(personalInfo.getLivingProvince());//现居住地址省份
        infoRequest.setLivingCity(personalInfo.getLivingCity());//现居住地址城市
        infoRequest.setLivingArea(personalInfo.getLivingArea());//现居住地址区
        infoRequest.setLivingAddress(personalInfo.getLivingAddress());//详细地址
        infoRequest.setEmail(personalInfo.getEmail());//电子邮箱
        infoRequest.setUpdateTime(personalInfo.getUpdateTime().getTime()* 1000l);//更新时间
        //联系人初始化
        this.personalInfoInitLinkManInfo(personalInfo, infoRequest);

        try {
            CompletableFuture<TianchengUapResponse> future = tianchengDataFlowService.personalInfo(infoRequest);
            future.whenComplete(dataBackFlowRetryCallBack(userId, FunctionCodeEnum.PERSONAL_INFO_FLOW, infoRequest));
            log.info("UserProfessionInfoBackFlowDubboServiceImpl.personalInfo tianchengRequest={} end", JSON.toJSON(infoRequest));
        } catch (Throwable t) {
            log.error("UserProfessionInfoBackFlowDubboServiceImpl.personalInfo tianchengRequest={} error", JSON.toJSON(infoRequest), t);
        }
    }

    private BiConsumer<TianchengUapResponse, Throwable> dataBackFlowRetryCallBack(String userId, FunctionCodeEnum functionCodeEnum, TianchengUapRequest tianchengUapRequest) {
        return (res, ex) -> {
            try {
                if (ex != null || !"0".equals(res.getStatus())) {
                    DataBackFlowRetryTaskRequestDTO retryTaskRequestDTO = new DataBackFlowRetryTaskRequestDTO();
                    retryTaskRequestDTO.setUserId(userId);
                    retryTaskRequestDTO.setBackflowData(JSON.toJSONString(tianchengUapRequest));
                    retryTaskRequestDTO.setFunctionCode(functionCodeEnum.getBodyFunctionCode());
                    dataBackFlowRetryDubboService.saveDataFlowRetryTask(retryTaskRequestDTO);
                }
            } catch (Exception e) {
                log.error("UserProfessionInfoBackFlowDubboServiceImpl.dataBackFlowRetryCallBack userId={},functionCodeEnum={}, tianchengUapRequest={}", userId, JSON.toJSONString(functionCodeEnum), JSON.toJSONString(tianchengUapRequest), e);
            }
        };
    }

    //联系人初始化
    private void personalInfoInitLinkManInfo(UserPersonalDubboInfoDTO userPersonalDubboInfoDTO, PersonalInfoRequest infoRequest) {
        List<LinkManDubboInfoDTO> linkManInfoList = userPersonalDubboInfoDTO.getLinkManInfoList();
        if (CollectionUtils.isEmpty(linkManInfoList)) {
            return;
        }
        List<PersonalInfoRequest.UserRelationRequest> userRelations = new ArrayList<>();
        for (LinkManDubboInfoDTO linkMan : linkManInfoList) {

            if(LinkManRelationEnum.LinkManOrderNoEnum.LINKMAN_1.getType() == linkMan.getOrderNo()){
                infoRequest.setContactName1(linkMan.getName());
                infoRequest.setContactPhone1(linkMan.getMobileNo());
                infoRequest.setContactRelation1(LinkManRelationEnum.getByEventType(linkMan.getRelation()).getDesc());
            }

            if(LinkManRelationEnum.LinkManOrderNoEnum.LINKMAN_2.getType() == linkMan.getOrderNo()){
                infoRequest.setContactName2(linkMan.getName());
                infoRequest.setContactPhone2(linkMan.getMobileNo());
                infoRequest.setContactRelation2(LinkManRelationEnum.getByEventType(linkMan.getRelation()).getDesc());
            }

            PersonalInfoRequest.UserRelationRequest userRelationReq = new PersonalInfoRequest.UserRelationRequest();
            userRelationReq.setContactName(linkMan.getName());
            userRelationReq.setContactPhone(linkMan.getMobileNo());
            userRelationReq.setUpdateTime(linkMan.getUpdateTime().getTime());
            userRelationReq.setUserId(String.valueOf(userPersonalDubboInfoDTO.getUserId()));
            userRelationReq.setContactRelation(LinkManRelationEnum.getByEventType(linkMan.getRelation()).getDesc());
            userRelations.add(userRelationReq);
        }
        infoRequest.setUserRelations(userRelations);
    }

    @Override
    public void professionInfo(String userId) {
        log.info("UserProfessionInfoBackFlowDubboServiceImpl.personalInfo userId={} start", userId);

        UserProfessionDubboInfoDTO professionInfo = userDataService.userProfessionInfo(userId);
        UserBasicInfoResponseDTO userBasicInfo = userBasicInfoService.getUserBaseInfo(userId);

        ProfessionInfoRequest infoRequest = new ProfessionInfoRequest();
        infoRequest.setUserId(professionInfo.getUserId());                   //用户id
        infoRequest.setMobilePhone(userBasicInfo.getMobileNo());             //手机号
        infoRequest.setCompanyName(professionInfo.getCompanyName());         //公司名称
        infoRequest.setCompanyProvince(professionInfo.getCompanyProvince()); //单位地址省份
        infoRequest.setCompanyCity(professionInfo.getCompanyCity());         //单位地址城市
        infoRequest.setCompanyArea(professionInfo.getCompanyArea());         //单位地址区
        infoRequest.setCompanyAddress(professionInfo.getCompanyAddress());   //单位详细地址
        infoRequest.setCompanyTel(professionInfo.getCompanyPhone());         //单位电话
        infoRequest.setDeparment(professionInfo.getDepartment());            //部门
        //infoRequest.setPosition(professionInfo.getPosition());               //职务
        //infoRequest.setIncome();           //收入
        //infoRequest.setWorkYears();        //工作年限
        //infoRequest.setWorkTotalYears();   //工作总工龄
        infoRequest.setCreateTime(professionInfo.getCreateTime().getTime()); //创建时间
        infoRequest.setUpdateTime(professionInfo.getUpdateTime().getTime()); //更新时间
        try {
            CompletableFuture<TianchengUapResponse> future = tianchengDataFlowService.professionInfo(infoRequest);
            future.whenComplete(dataBackFlowRetryCallBack(userId, FunctionCodeEnum.PROFESSION_INFO_FLOW, infoRequest));
            log.info("UserProfessionInfoBackFlowDubboServiceImpl.professionInfo tianchengRequest={} end", JSON.toJSON(infoRequest));
        } catch (Throwable t) {
            log.error("UserProfessionInfoBackFlowDubboServiceImpl.professionInfo tianchengRequest={} error", JSON.toJSON(infoRequest), t);
        }
    }

    @Override
    public void changeMobileNo(String userId) {
        log.info("UserProfessionInfoBackFlowDubboServiceImpl.ChangeMobileNo userId={} start", userId);
        UcAccount infoDTO = userAccountMapperExt.selectByPrimaryKey(userId);
        MobileChangeRecord changeRecord =  mobileChangeRecordMapper.selectMobileChangeRecord(userId);

        ChangeMobileNoRequest infoRequest = new ChangeMobileNoRequest();
        infoRequest.setUserId(userId);
        infoRequest.setNewMobilePhone(privacyMasks.decryptPrivacy(infoDTO.getMobileNo()));
        infoRequest.setMobilePhone(privacyMasks.decryptPrivacy(changeRecord.getMobileNo()));
        infoRequest.setRemark(MobileChangeRecordEnum.ChangeTypeEnum.of(changeRecord.getChangeType()).getDesc());

        try {
            CompletableFuture<TianchengUapResponse> completableFuture = tianchengDataFlowService.changeMobileNo(infoRequest);
            completableFuture.whenComplete(dataBackFlowRetryCallBack(userId, FunctionCodeEnum.MOBILE_NO_FLOW, infoRequest));
            log.info("UserProfessionInfoBackFlowDubboServiceImpl.changeMobileNo tianchengRequest={} end", JSON.toJSON(infoRequest));
        } catch (Throwable t) {
            log.error("UserProfessionInfoBackFlowDubboServiceImpl.changeMobileNo tianchengRequest={} error", JSON.toJSON(infoRequest), t);
        }
    }

}


